<template>
  <div>
    <!--    面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--    卡片视图区域-->
    <el-card>
      <el-alert
          title="注意:只允许为第三级分类设置相关参数！"
          type="warning"
          show-icon
          effect="dark"
          :closable="false"


      >
      </el-alert>
      <!--      选择商品分类区域-->
      <el-row>
        <el-col>
          <span>选择商品分类:</span>
          <!--          选择商品的级联选择框-->
          <el-cascader
              expand-trigger="hover"
              v-model="selectCateKeys"
              :options="cateList"
              :props="cascaderProps"
              clearable
              @change="handleChange"
          >
          </el-cascader>
        </el-col>
      </el-row>
      <!--      tab页签区域-->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!--        添加动态参数面板-->
        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled="isBtnDisabled" size="mini" type="primary" @click="addParamsDialogVisible=true">添加参数
          </el-button>
          <!--          动态参数表格-->
          <el-table :data="manyTableData"
                    border
                    stripe
          >
            <el-table-column type="expand">
              <template slot-scope="scope">

                <el-tag
                    closable v-for="(item,index) in scope.row.attr_vals"
                    :key="index"
                    @close="handleTagClosed(index,scope.row)"
                >
                  {{item}}
                </el-tag>

<!--                输入文本框-->
                <el-input
                    style="width: 200px"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">
                  编辑
                </el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>


          </el-table>
        </el-tab-pane>
        <!--        添加静态属性面板-->
        <el-tab-pane label="静态属性" name="only">
          <el-button :disabled="isBtnDisabled" size="mini" type="primary" @click="addParamsDialogVisible=true">添加属性
          </el-button>
          <!--          静态属性表格-->
          <el-table :data="onlyTableData"
                    border
                    stripe
          >
            <el-table-column type="expand">
              <template slot-scope="scope">

                <el-tag
                    closable v-for="(item,index) in scope.row.attr_vals"
                    :key="index"
                    @close="handleTagClosed(index,scope.row)"
                >
                  {{item}}
                </el-tag>

                <!--                输入文本框-->
                <el-input
                    style="width: 200px"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">
                  编辑
                </el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>


          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!--    添加参数对话框-->
    <el-dialog
        :title="'添加'+this.titleText"
        :visible.sync="addParamsDialogVisible"
        width="50%"
        @close="handleAddDialogClosed"
    >
      <!--     内容主体区域-->
      <el-form :model="addParamsForm"
               :rules="addParamsFormRules"
               ref="addParamsFormRef"
               label-width="auto"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input
              v-model.trim="addParamsForm.attr_name"
              @keyup.enter.native="addParams"
          ></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button
            type="primary"
            @click="addParams"

        >确 定</el-button>
      </span>
    </el-dialog>
    <!--    修改参数对话框-->
    <el-dialog
        :title="'修改'+this.titleText"
        :visible.sync="editParamsDialogVisible"
        width="50%"
        @close="handleEditDialogClosed"
    >
      <!--     内容主体区域-->
      <el-form :model="editParamsForm"
               :rules="editParamsFormRules"
               ref="editParamsFormRef"
               label-width="auto"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model.trim="editParamsForm.attr_name"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Params",
  data() {
    return {
      // 商品分类列表
      cateList: [],
      cascaderProps: {
        checkStrictly: true,
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 选中分类的id数组
      selectCateKeys: [],
      // 页签默认选中的名称
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 控制添加参数对话框的显示隐藏
      addParamsDialogVisible: false,
      // 添加参数表单数据对象
      addParamsForm: {
        attr_name: ''
      },
      // 添加参数表单的验证规则
      addParamsFormRules: {
        attr_name: [
          {required: true, message: '请输入参数名称', trigger: 'blur'}
        ]
      },
      // 控制修改参数表单的显示隐藏
      editParamsDialogVisible: false,
      // 修改参数表单数据的对象
      editParamsForm: {},
      // 修改参数表单的验证规则
      editParamsFormRules: {
        attr_name: [
          {required: true, message: '请输入参数名称', trigger: 'blur'}
        ]
      },

    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 定义添加参数和添加属性按钮是否禁用
    isBtnDisabled() {
      if (this.selectCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 当前选中的三级分类id
    cateId() {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2]
      }
      return null
    },
    // 动态计算对话框标题的文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }

    }
  },
  methods: {
    // 级联选择器发生改变触发的事件
    handleChange() {
      this.getParamsData()
    },
    // 获取商品分类列表
    async getCateList() {
      const {data: res} = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.cateList = res.data
      console.log(this.cateList)
    },
    // 获取动态参数或静态属性
    async getParamsData() {
      // 进入判断说明选中的不是三级分类
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 说明选中的是三级分类
      console.log(this.selectCateKeys)
      // 根据所选的三级分类id获取对应的参数列表
      const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {sel: this.activeName}
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      console.log('res111', res.data)



      res.data.forEach(item => {
        // 将字符串切割成数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" "):[]
        // 控制文本框的显示隐藏
        item.inputVisible = false
        // 文本框输入的值
        item.inputValue = ''

      })


      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 处理标签页改变的回调
    handleTabClick() {
      console.log(this.activeName)
      // 标签页改变也要再次发请求
      this.getParamsData()
    },
    // 处理添加参数对话框的关闭
    handleAddDialogClosed() {
      this.$refs.addParamsFormRef.resetFields()
    },
    // 点击按钮添加参数的事件
    addParams() {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }

        this.$message.success('添加参数成功')
        this.getParamsData()
        this.addParamsDialogVisible = false


      })
    },
    // 点击按钮修改参数表单的事件
    editParams() {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return

        const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }

        this.$message.success('修改成功')
        this.getParamsData()
        this.editParamsDialogVisible = false
      })
    },
    // 重置修改参数表单的事件
    handleEditDialogClosed() {
      this.$refs.editParamsFormRef.resetFields()
    },
    // 展示修改参数的对话框
    async showEditDialog(attr_id) {
      console.log('attr_id', attr_id)
      const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editParamsForm = res.data
      console.log(this.editParamsForm)
      this.editParamsDialogVisible = true
    },
    // 删除参数(根据id删除)
    async removeParams(attr_id) {
      console.log('删除', attr_id)
      const confirmResult = await this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消')
      }

      const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('删除成功')
      this.getParamsData()

    },
    // 点击enter,或者光标失去焦点进行文本框的输入
   async handleInputConfirm(row){
     console.log('row',row)
      if(row.inputValue.trim().length === 0){
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果没有return说明用户输入了
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      // 输入完之后将文本框隐藏
      row.inputVisible = false

      this.saveAttrVals(row)




    },
    // 对参数属性值进行保存到后台数据库
   async saveAttrVals(row){
      // 将数据保存到后台中作持久化操作
      const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        // 放到后台服务器是以字符串到形式,所以要将数组拼接成字符串
        attr_vals:row.attr_vals.join(' ')
      })
      if(res.meta.status !==200){
        return this.$message.error(res.meta.msg)
      }

      this.$message.success('修改参数项成功')
    },
    // 点击按钮展示文本输入框
    showInput(currentInput){
      currentInput.inputVisible = true
      // 让文本自动获取焦点
      // $nextTick方法的作用是当页面重新渲染,才会调用指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });

    },
    // 删除对应参数可选项
    handleTagClosed(tagIndex,row){
      row.attr_vals.splice(tagIndex,1)
      this.saveAttrVals(row)
    }



  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}

.el-cascader {
  margin-left: 15px;
}
.el-tag{
  margin: 10px;

}
</style>
